# coding=UTF-8
from django.http import Http404, HttpResponse
from django.contrib.contenttypes.models import ContentType
from djopping_core.models import Product
from djopping_favs.models import FavouriteItem
from django.contrib.auth.models import User

FAVOURITE_ITEMS_TEMPLATE = 'djopping/favs/favourite_item.html'

#AJAX views
def add_product(request, product_id):
    """
    Adds an item (in this case, a product) to the favourites list of a User.
    """
    if request.method != 'POST' or not request.user.is_authenticated():
        raise Http404
    post = request.POST.copy()
    try:
        product = Product.objects.get(id=product_id)
    except Product.DoesNotExist, e:
        raise Http404
    try:
        if str(request.user.id) == str(post['user_id']):
            ctype = ContentType.objects.get_for_model(product)
            user = User.objects.get(id=post['user_id'])
            try:
                favourite = FavouriteItem.objects.get(
                    content_type=ctype,
                    object_id=product.id,
                    user=user)
            except Exception, e:
                print e
                try:
                    favourite = FavouriteItem(
                        content_type=ctype,
                        object_id=product.id,
                        user=user)
                    favourite.save()
                except Exception, e:
                    print e
        else:
            raise Http404
    except User.DoesNotExist, e:
        raise Http404

    return HttpResponse('0K')

def del_product(request, product_id):
    """
    Deletes an item (in this case, a product) from the favourites list of a
    User.
    """
    if request.method != 'POST' or not request.user.is_authenticated():
        raise Http404
    post = request.POST.copy()
    try:
        product = Product.objects.get(id=product_id)
    except Product.DoesNotExist, e:
        print e
        raise Http404
    try:
        if str(request.user.id) == str(post['user_id']):
            ctype = ContentType.objects.get_for_model(product)
            user = User.objects.get(id=post['user_id'])
            favourite = FavouriteItem.objects.get(
                content_type=ctype,
                object_id=product.id,
                user=user)
            favourite.delete()
        else:
            raise Http404
    except Exception, e:
        print e
        raise Http404

    return HttpResponse('0K')

def get_favourites(request):
    from djopping_favs.utils import favourites
    from django.template import Context
    from django.template.loader import get_template

    # Tengo que pedir solo HttpResponse.content porque sino me renderiza
    # también el mimetype, osea, me hace un __str__ feo.
    return HttpResponse(
        get_template(FAVOURITE_ITEMS_TEMPLATE).render(
            Context(favourites(request))))
